<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="icon" href="data:;base64,iVBORw0KGgo=">
  <style>
    body {
      margin:0;
      padding:0;
      background-color:#303030;
    }

    #streamStage {
      position:fixed;
      top:0;
      left:0;
      width:100%;
      height:100%;
    }

    #streamStage:before {
      content: '';
      box-sizing: border-box;
      position: absolute;
      top: 50%;
      left: 50%;
      width: 2rem;
      height: 2rem;
      margin-top: -1rem;
      margin-left: -1rem;
    }

    #stream {
      max-height: 100%;
      max-width: 100%;
      margin: auto;
      position: absolute;
      top: 0; left: 0; bottom: 0; right: 0;
    }
  </style>
</head>
<body>
  <div id="streamtage">
    <video controls autoplay muted playsinline id="stream"></video>
  </div>

  <script>
    function startWebRTC() {
        var config = {
            sdpSemantics: 'unified-plan'
        };

        if (document.getElementById('use-stun') && document.getElementById('use-stun').checked) {
          config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
        }

        pc = new RTCPeerConnection(config);
        pc.addTransceiver('video', {direction: 'recvonly'});
        //pc.addTransceiver('audio', {direction: 'recvonly'});
        pc.addEventListener('track', function(evt) {
          console.log("track event " + evt.track.kind);
            if (evt.track.kind == 'video') {
                if (document.getElementById('stream')) {
                  document.getElementById('stream').srcObject = evt.streams[0];
                }
            } else {
                if (document.getElementById('audio'))
                  document.getElementById('audio').srcObject = evt.streams[0];
            }
        });

        const urlSearchParams = new URLSearchParams(window.location.search);
        const params = Object.fromEntries(urlSearchParams.entries());

        fetch(window.location.href, {
          body: JSON.stringify({
              type: 'request',
              res: params.res
          }),
          headers: {
              'Content-Type': 'application/json'
          },
          method: 'POST'
        }).then(function(response) {
          return response.json();
        }).then(function(answer) {
          pc.remote_pc_id = answer.id;
          return pc.setRemoteDescription(answer);
        }).then(function() {
          return pc.createAnswer();
        }).then(function(answer) {
          return pc.setLocalDescription(answer);
        }).then(function() {
            // wait for ICE gathering to complete
            return new Promise(function(resolve) {
                if (pc.iceGatheringState === 'complete') {
                    resolve();
                } else {
                    function checkState() {
                        if (pc.iceGatheringState === 'complete') {
                            pc.removeEventListener('icegatheringstatechange', checkState);
                            resolve();
                        }
                    }
                    pc.addEventListener('icegatheringstatechange', checkState);
                }
            });
        }).then(function(answer) {
          var offer = pc.localDescription;

          return fetch(window.location.href, {
            body: JSON.stringify({
                type: offer.type,
                id: pc.remote_pc_id,
                sdp: offer.sdp,
            }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
          })
        }).then(function(response) {
            return response.json();
        }).catch(function(e) {
            alert(e);
        });
    }

    function stopWebRTC() {
        setTimeout(function() {
            pc.close();
        }, 500);
      }
  </script>

  <script>
    window.onload = function() {
      startWebRTC();
    }
  </script>
</body>
</html>
